﻿using System;
using UnityEngine;
using UnityEngine.Playables;

[Serializable]
public class MovementBehaviour : PlayableBehaviour
{
    #region Properties
    public Vector3 Direction = Vector3.up;
    public float Distance = 0f;
    public Space SpaceMode = Space.Self;
    #endregion

    #region Self
    private Transform target;
    private bool firstTime = true;

    private Vector3 originLocalPosition;
    private Vector3 destinationLocalPosition;

    private Vector3 originPosition;
    private Vector3 destinationPosition;
    #endregion

    #region Func
    public void Init(Transform target)
    {
        this.target = target;
    }
    #endregion

    #region PlayableBehaviour
    public override void OnBehaviourPlay(Playable playable, FrameData info)
    {

    }

    public override void ProcessFrame(Playable playable, FrameData info, object playerData)
    {
        if (null == target)
        {
            return;
        }

        if (firstTime)
        {
            firstTime = false;

            if (SpaceMode == Space.Self)
            {
                originLocalPosition = target.localPosition;
                destinationLocalPosition = originLocalPosition + (Direction * Distance);
            }
            else
            {
                originPosition = target.position;
                destinationPosition = originPosition + (Direction * Distance);
            }
        }

        if (SpaceMode == Space.Self)
        {
            target.localPosition = Vector3.Lerp(originLocalPosition, destinationLocalPosition, (float)(playable.GetTime() / playable.GetDuration()));
        }
        else
        {
            target.position = Vector3.Lerp(originPosition, destinationPosition, (float)(playable.GetTime() / playable.GetDuration()));
        }
    }

    public override void OnBehaviourPause(Playable playable, FrameData info)
    {

    }
    #endregion
}
